import React, { useState } from 'react';
import { AppScreen, Rulebook, AiPrompts, GameData, GameSettings, ChatMessage } from '../types';
import { saveGame, DEFAULT_MACRO_FUNCTIONS } from '../services/gameSaveService';
import LoadingSpinner from './LoadingSpinner';
import { v4 as uuidv4 } from 'uuid';
import { CALCULATION_HELPER_AI_TEMPLATE, HYBRID_STRUCTURED_DATA_TEMPLATE, NARRATIVE_AI_WITH_CALCS_TEMPLATE, TOOL_CALLING_TEMPLATE } from '../constants';
import RulebookTuningModal from './PromptDiscussionModal'; // Placeholder for the new modal
import { SparklesIcon } from './icons';

interface CreateGameScreenProps {
  setCurrentScreen: (screen: AppScreen) => void;
  setActiveGame: (gameData: GameData) => void;
  settings: GameSettings;
  showToast: (message: string, type?: 'success' | 'error') => void;
  onGameCreated: (gameData: GameData) => void;
}

const CreateGameScreen: React.FC<CreateGameScreenProps> = ({ setCurrentScreen, setActiveGame, settings, showToast, onGameCreated }) => {
  const [rulebook, setRulebook] = useState<Rulebook>({
    gameName: '',
    backgroundStory: '',
    rules: '',
  });
  const [isLoading, setIsLoading] = useState(false);
  const [isTuningModalOpen, setIsTuningModalOpen] = useState(false);
  // We don't need to save chat history at this stage, so we'll just manage it for the modal session
  const [rulebookChatHistory, setRulebookChatHistory] = useState<ChatMessage[]>([]);


  const handleRulebookChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setRulebook({ ...rulebook, [e.target.name]: e.target.value });
  };
  
  const createGameAndEnter = async () => {
    if (!rulebook.gameName || !rulebook.backgroundStory || !rulebook.rules) {
      showToast("请填写所有游戏基本信息。", "error");
      return;
    }
    setIsLoading(true);

    // Create a new game with empty prompts
    const initialAiPrompts: AiPrompts = {
      scenarioGenerationPrompt: "",
      statusPanelPrompt: "",
      keyInfoExtractionPrompt: "",
      calculationHelperSystemPrompt: CALCULATION_HELPER_AI_TEMPLATE,
      narrativeWithCalcsSystemPrompt: NARRATIVE_AI_WITH_CALCS_TEMPLATE,
      hybridStructuredDataSystemPrompt: HYBRID_STRUCTURED_DATA_TEMPLATE,
      toolCallingSystemPrompt: TOOL_CALLING_TEMPLATE,
    };

    const newGameData: GameData = {
      id: uuidv4(),
      rulebook,
      aiPrompts: initialAiPrompts,
      macroFunctions: JSON.parse(JSON.stringify(DEFAULT_MACRO_FUNCTIONS)), // Deep copy
      gameHistory: [],
      aggregatedKeyInfo: '',
      lastPlayedTimestamp: 0,
      rulebookChatHistory: rulebookChatHistory,
    };

    try {
      await saveGame(newGameData);
      showToast(`游戏 "${newGameData.rulebook.gameName}" 创建成功！`, "success");
      onGameCreated(newGameData);
    } catch (e) {
        showToast(`创建游戏失败: ${e instanceof Error ? e.message : '未知错误'}`, "error");
        setIsLoading(false);
    }
  };

  const formFieldStyles = "w-full p-3 bg-gray-700 border border-gray-600 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-colors text-gray-100 placeholder-gray-400";
  const labelStyles = "block text-sm font-medium text-gray-300 mb-1";

  return (
    <>
    <div className="min-h-screen flex flex-col items-center justify-center p-4 bg-gray-900 text-gray-100">
      <div className="w-full max-w-2xl bg-gray-800 p-8 rounded-xl shadow-2xl space-y-6">
        <h2 className="text-3xl font-bold text-center text-transparent bg-clip-text bg-gradient-to-r from-purple-400 via-pink-500 to-red-500">
          创建新游戏
        </h2>
        <p className="text-sm text-gray-400 text-center">请填写游戏的核心设定。AI提示词将在进入游戏后生成。</p>

        {isLoading ? (
          <div className="flex justify-center my-4"><LoadingSpinner text="正在创建世界..." /></div>
        ) : (
          <>
            <div>
              <label htmlFor="gameName" className={labelStyles}>游戏名称</label>
              <input type="text" name="gameName" id="gameName" value={rulebook.gameName} onChange={handleRulebookChange} className={formFieldStyles} placeholder="例如：失落的阿尔卡迪亚编年史" />
            </div>
            <div>
              <label htmlFor="backgroundStory" className={labelStyles}>背景设定</label>
              <textarea name="backgroundStory" id="backgroundStory" value={rulebook.backgroundStory} onChange={handleRulebookChange} rows={4} className={formFieldStyles} placeholder="描述游戏的时代背景、主要冲突、世界观等。"></textarea>
            </div>
            <div>
              <div className="flex justify-between items-center mb-1">
                <label htmlFor="rules" className={labelStyles}>游戏规则书</label>
                <button 
                    onClick={() => setIsTuningModalOpen(true)}
                    className="flex items-center gap-1 text-xs px-2 py-1 bg-sky-600 hover:bg-sky-700 rounded-md text-white transition-colors"
                    title="与AI讨论优化"
                    disabled={!rulebook.gameName || !rulebook.backgroundStory}
                >
                    <SparklesIcon className="w-4 h-4" />
                    <span>AI协助编写</span>
                </button>
              </div>
              <textarea name="rules" id="rules" value={rulebook.rules} onChange={handleRulebookChange} rows={6} className={formFieldStyles} placeholder="详细定义游戏的核心机制、角色成长、战斗系统（如果有）、物品效果、胜利/失败条件等。AI将依据此规则书生成游戏内容。"></textarea>
            </div>
            <div className="flex justify-between items-center pt-4">
              <button onClick={() => setCurrentScreen(AppScreen.MainMenu)} className="px-6 py-3 bg-gray-600 hover:bg-gray-700 rounded-md shadow-md transition-transform transform hover:scale-105">返回主菜单</button>
              <button 
                onClick={createGameAndEnter} 
                className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-md shadow-md transition-transform transform hover:scale-105"
                data-guide-id="create-and-enter-btn"
              >
                创建并进入游戏
              </button>
            </div>
          </>
        )}
      </div>
    </div>
    {isTuningModalOpen && (
        <RulebookTuningModal
            isOpen={isTuningModalOpen}
            onClose={() => setIsTuningModalOpen(false)}
            initialRules={rulebook.rules}
            initialChatHistory={rulebookChatHistory}
            gameName={rulebook.gameName}
            backgroundStory={rulebook.backgroundStory}
            settings={settings}
            showToast={showToast}
            onFinalize={(newRules, newHistory) => {
                setRulebook(prev => ({...prev, rules: newRules}));
                setRulebookChatHistory(newHistory);
                setIsTuningModalOpen(false);
            }}
        />
    )}
    </>
  );
};

export default CreateGameScreen;